﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace personalplaner.business.extensions
{
    public static class StringExtensions
    {
		/// <summary>
		/// Parses a string to a nullable DateTime.
		/// </summary>
		/// <param name="stringValue">The string value.</param>
		/// <returns>The parsed value or null.</returns>
		public static DateTime? ParseToNullableDateTimeValue(this string stringValue)
		{
			DateTime? value = null;

			DateTime dateTimeValue;
			if (DateTime.TryParse(stringValue, out dateTimeValue))
			{
				value = dateTimeValue;
			}
			else
			{
				if (!string.IsNullOrEmpty(stringValue) && stringValue.Length == 8)
				{
					var strDate = stringValue.Substring(0, 4) + "/" + stringValue.Substring(4, 2) + "/" + stringValue.Substring(6, 2);

					if (DateTime.TryParse(strDate, out dateTimeValue))
					{
						value = dateTimeValue;
					}
				}
			}

			return value;
		}

		/// <summary>
		/// Parses a string to a nullable DateTime.
		/// </summary>
		/// <param name="stringValue">The string value.</param>
		/// <returns>The parsed value or null.</returns>
		public static DateTime ToDateTime(this string stringValue)
		{
			DateTime? value = stringValue.ParseToNullableDateTimeValue();

			if (value == null)
				value = DateTime.Now;

			return value.Value;
		}

		/// <summary>
		/// Removes all leading and trailing white-space characters from the current System.String object
		/// or null if the string is null.
		/// </summary>
		/// <param name="value">The string value.</param>
		/// <returns>
		/// The string that remains after all white-space characters are removed from
		/// the start and end of the current string or null.
		/// </returns>
		public static string TrimNullable(this string value)
		{
			if (value == null)
			{
				return value;
			}
			else
			{
				return value.Trim();
			}
		}
    }
}
